package cc.wsyw126.java.jvm.WaitNotify;

import cc.wsyw126.java.model.User;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/4/24.
 */
public class TestWaitNotify {
    private User user = new User();
    class NotifyThread extends Thread{
        public NotifyThread(String name) {
            super(name);
        }
        public void run() {
            try {
                sleep(3000);//推迟3秒钟通知
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (user) {
                user.setName("false");
                user.notifyAll();
            }
        }
    }

    class WaitThread extends Thread {
        public WaitThread(String name) {
            super(name);
        }

        public void run() {

            synchronized (user) {
                while (user.getName()!="false") {
                    System.out.println(getName() + " begin waiting!");
                    long waitTime = System.currentTimeMillis();
                    try {
                        user.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    waitTime = System.currentTimeMillis() - waitTime;
                    System.out.println("wait time :"+waitTime);
                }
                System.out.println(getName() + " end waiting!");
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Main Thread Run!");
        TestWaitNotify test = new TestWaitNotify();
        NotifyThread notifyThread =test.new NotifyThread("notify01");
        WaitThread waitThread01 = test.new WaitThread("waiter01");
        WaitThread waitThread02 = test.new WaitThread("waiter02");
        WaitThread waitThread03 = test.new WaitThread("waiter03");
        waitThread01.start();
        waitThread02.start();
        waitThread03.start();
        TimeUnit.SECONDS.sleep(2);
        notifyThread.start();

    }
}
